package com.ksyun.whcg.zhanglulu;
import java.util.*;
/**
 * @Author: 张露露
 * @Description: 金山云作业
 * @DateTime: 2023/4/21 9:19
 **/
public class StringUtil {
    //反转字符
    public static String reverse(String str) {
        return new StringBuilder(str).reverse().toString();

    }

    // 统计每个字母出现次数
    public static Map<Character, Integer> countChars(String str) {
        Map<Character, Integer> counts = new HashMap<>();
        for (char c : str.toCharArray()) {
            counts.put(c, counts.getOrDefault(c, 0) + 1);
        }
        return counts;
    }


    // 找出出现次数最多的字母及其次数
    public static void printMostFrequentChar(String str) {
        Map<Character, Integer> counts = countChars(str);
        char mostFrequent = ' ';
        int maxCount = 0;
        for (char c : counts.keySet()) {
            int count = counts.get(c);
            if (count > maxCount) {
                maxCount = count;
                mostFrequent = c;
            }
        }
        System.out.printf("Most frequent char: %c, count: %d\n", mostFrequent, maxCount);
    }


    // 找出不含有重复字符的最长子串
    public static String longestSubstringWithoutRepeatingChars(String str) {
        String longestSubstring = "";
        Set<Character> seen = new HashSet<>();
        for (int i = 0; i < str.length(); i++) {
            for (int j = i; j < str.length(); j++) {
                char c = str.charAt(j);
                if (!seen.contains(c)) {
                    seen.add(c);
                    String substring = str.substring(i, j + 1);
                    if (substring.length() > longestSubstring.length()) {
                        longestSubstring = substring;
                    }
                } else {
                    seen.clear();
                    break;
                }
            }
        }
        return longestSubstring;
    }

}
